package org.lc.cmd.plugin;

import org.lc.cmd.CmdBuilder;
import org.lc.cmd.Command;
import org.lc.cmd.CommandRegistry;
import org.lc.cmd.impl.bridge.HttpServerBridge;
import org.lc.cmd.plugin.anno.Cmd;
import org.lc.cmd.util.CollectionUtil;
import org.lc.cmd.util.ContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration
@EnableConfigurationProperties()
@Import({ContextUtil.class, HttpServerBridge.HttpServerController.class})
@ComponentScan(basePackages = "org.lc.cmd.plugin.scan")
public class CmdStarterAutoConfiguration implements ApplicationRunner {
    @Autowired
    private CmdBuilder cmdBuilder;

    @Autowired
    private CommandRegistry registry;

    @Override
    public void run(ApplicationArguments args) {
        Collection<Object> cmds = ContextUtil.getBeansWithAnnotation(Cmd.class).values();
        Map<Class<?>, List<Command>> commands = new HashMap<>();
        for (Object cmd : cmds) {
            Class<?> clazz = cmd.getClass();
            List<Command> cmdList = cmdBuilder.buildCommands(clazz);
            if (CollectionUtil.isNotEmpty(cmdList)) {
                commands.put(clazz, cmdList);
            }
        }
        List<Command> commandList = new ArrayList<>(commands.size());
        commands.forEach((k, v) -> commandList.addAll(v));
        registry.registerCommands(commandList);
    }
}
